package com.sihai.ehr.service.impl;

import com.sihai.core.DataAccessor;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.Sorter;
import com.sihai.ehr.model.sys.Role;
import com.sihai.ehr.service.RoleService;
import com.sihai.ehr.web.pojo.RolePojo;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * author: wxn
 * since: 13-2-4 Time: 上午11:31
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    private DataAccessor dataAccessor;

    @Override
    public Role getRole(Long id) throws Exception {
        Assert.notNull(id, "role id is required");
        return dataAccessor.get(Role.class, id);
    }

    @Override
    public void save(Role role) throws Exception {
        Assert.notNull(role, "role is required");
        dataAccessor.save(role);
    }

    @Override
    public LimitedList<RolePojo> findByTopOrganization(Long organizationId, Limit limit, Sorter sorter) throws Exception {
        Assert.notNull(organizationId, "organizationId is required");
        String hql = "select new com.sihai.ehr.web.pojo.RolePojo(rl.id, d, rl) from Role rl right join rl.duty d where d.cancel=0 and (d.organization.id = ? or d.organization.topOrganization.id = ?)";
        return dataAccessor.findByHql(RolePojo.class, hql, new Object[]{organizationId, organizationId}, limit, sorter);
    }

    @Override
    public LimitedList<Role> find(Role role, Limit limit, Sorter sorter) throws Exception {
        if(role == null){
            return dataAccessor.findByHql(Role.class, "from Role", null, limit, sorter);
        }
        return null;
    }

    @Override
    public void delete(Long id) throws Exception {
        Role role = getRole(id);
        Assert.notNull(role, "role is required");
        dataAccessor.delete(role);
    }
}
